package me.lxw.blogsystem.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库工具类
 * 
 * @author 梁兴威
 * 
 */
public class DBUtils {
    private final static String fileName = "jdbc";
    // 1. 创建私有的属性*（连接数据库必要的四个变量）：driver url user password
    private static String DRIVER = PropertiesUtil.getProperty(fileName, "db.driver");
    private static String URL = PropertiesUtil.getProperty(fileName, "db.url");
    private static String USER = PropertiesUtil.getProperty(fileName, "db.user");
    private static String PASSWORD = PropertiesUtil.getProperty(fileName, "db.password");

    // 2. 将构造函数私有化
    private DBUtils() {

    }

    // 3.将注册驱动写入静态代码块
    // 其中静态代码块只执行一次。构造代码块在每次创建对象是都会执行。
    static {
        // 注册驱动
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接Connection
     * 
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    /**
     * 释放资源
     * 
     * @param conn
     * @param st
     * @param rs
     * @throws SQLException
     */
    public static void closeResource(Connection conn, Statement st, ResultSet rs) throws SQLException {
        rs.close();
        st.close();
        conn.close();
    }

    /**
     * 释放资源
     * 
     * @param conn
     * @param st
     * @param rs
     * @throws SQLException
     */
    public static void closeResource(Connection conn, Statement st) throws SQLException {
        st.close();
        conn.close();
    }
}
